package top.yokey.android.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.style.ChasingDots;
import com.github.ybq.android.spinkit.style.Circle;
import com.github.ybq.android.spinkit.style.CubeGrid;
import com.github.ybq.android.spinkit.style.DoubleBounce;
import com.github.ybq.android.spinkit.style.FadingCircle;
import com.github.ybq.android.spinkit.style.FoldingCube;
import com.github.ybq.android.spinkit.style.Pulse;
import com.github.ybq.android.spinkit.style.RotatingCircle;
import com.github.ybq.android.spinkit.style.RotatingPlane;
import com.github.ybq.android.spinkit.style.ThreeBounce;
import com.github.ybq.android.spinkit.style.WanderingCubes;
import com.github.ybq.android.spinkit.style.Wave;

@SuppressWarnings("ALL")
public class PullRefreshView extends RelativeLayout {

    private final int STATE_LOAD = 0;
    private final int STATE_EMPTY = 1;
    private final int STATE_ERROR = 2;
    private final int STATE_COMPLETE = 3;

    private boolean isError = false;
    private boolean canRefresh = true;
    private boolean canLoadMore = true;
    private Context context = getContext();
    private OnRefreshListener onRefreshListener = null;
    //数据列表
    private SwipeRefreshLayout swipeRefreshLayout = new SwipeRefreshLayout(context);
    private RecyclerView recyclerView = new RecyclerView(context);
    private SpinKitView spinKitView = new SpinKitView(context);
    //加载中的
    private SpinKitView loadSpinKitView = new SpinKitView(context);
    private AppCompatTextView loadTextView = new AppCompatTextView(context);
    private RelativeLayout loadRelativeLayout = new RelativeLayout(context);
    //数据为空
    private AppCompatImageView emptyImageView = new AppCompatImageView(context);
    private AppCompatTextView emptyTextView = new AppCompatTextView(context);
    private RelativeLayout emptyRelativeLayout = new RelativeLayout(context);
    //加载失败
    private AppCompatImageView errorImageView = new AppCompatImageView(context);
    private AppCompatTextView errorTextView = new AppCompatTextView(context);
    private RelativeLayout errorRelativeLayout = new RelativeLayout(context);

    public PullRefreshView(Context context) {

        super(context);
        initialization();

    }

    public PullRefreshView(Context context, AttributeSet attrs) {

        super(context, attrs);
        initialization();

    }

    public PullRefreshView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
        initialization();

    }

    //初始化

    private int dp2Px(int dp) {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

    }

    private void initialization() {

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        swipeRefreshLayout.setColorSchemeColors(PullRefreshViewHelper.get().getColors());
        swipeRefreshLayout.setLayoutParams(layoutParams);
        addView(swipeRefreshLayout);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutParams(layoutParams);
        swipeRefreshLayout.addView(recyclerView);
        //加载中的
        layoutParams = new RelativeLayout.LayoutParams(dp2Px(48), dp2Px(48));
        layoutParams.setMargins(0, dp2Px(120), 0, 0);
        layoutParams.addRule(CENTER_HORIZONTAL);
        setLoadStyle();
        loadSpinKitView.setColor(PullRefreshViewHelper.get().getLoadColor());
        loadSpinKitView.setLayoutParams(layoutParams);
        loadSpinKitView.setId(View.generateViewId());
        loadRelativeLayout.addView(loadSpinKitView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(dp2Px(48), dp2Px(16), dp2Px(48), 0);
        layoutParams.addRule(BELOW, loadSpinKitView.getId());
        layoutParams.addRule(CENTER_HORIZONTAL);
        loadTextView.setTextSize(PullRefreshViewHelper.get().getTextSize());
        loadTextView.setText(PullRefreshViewHelper.get().getLoadText());
        loadTextView.setTextColor(PullRefreshViewHelper.get().getLoadColor());
        loadTextView.setLayoutParams(layoutParams);
        loadRelativeLayout.addView(loadTextView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        loadRelativeLayout.setLayoutParams(layoutParams);
        addView(loadRelativeLayout);
        //数据为空
        layoutParams = new RelativeLayout.LayoutParams(dp2Px(64), RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, dp2Px(120), 0, 0);
        layoutParams.addRule(CENTER_HORIZONTAL);
        emptyImageView.setImageResource(PullRefreshViewHelper.get().getEmptyImage());
        emptyImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        emptyImageView.setLayoutParams(layoutParams);
        emptyImageView.setId(View.generateViewId());
        emptyRelativeLayout.addView(emptyImageView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(dp2Px(48), dp2Px(16), dp2Px(48), 0);
        layoutParams.addRule(BELOW, emptyImageView.getId());
        layoutParams.addRule(CENTER_HORIZONTAL);
        emptyTextView.setTextSize(PullRefreshViewHelper.get().getTextSize());
        emptyTextView.setText(PullRefreshViewHelper.get().getEmptyText());
        emptyTextView.setTextColor(PullRefreshViewHelper.get().getEmptyColor());
        emptyTextView.setLayoutParams(layoutParams);
        emptyRelativeLayout.addView(emptyTextView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        emptyRelativeLayout.setLayoutParams(layoutParams);
        addView(emptyRelativeLayout);
        //加载失败
        layoutParams = new RelativeLayout.LayoutParams(dp2Px(64), RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, dp2Px(120), 0, 0);
        layoutParams.addRule(CENTER_HORIZONTAL);
        errorImageView.setImageResource(PullRefreshViewHelper.get().getErrorImage());
        errorImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        errorImageView.setLayoutParams(layoutParams);
        errorImageView.setId(View.generateViewId());
        errorRelativeLayout.addView(errorImageView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(dp2Px(48), dp2Px(16), dp2Px(48), 0);
        layoutParams.addRule(BELOW, errorImageView.getId());
        layoutParams.addRule(CENTER_HORIZONTAL);
        errorTextView.setTextSize(PullRefreshViewHelper.get().getTextSize());
        errorTextView.setText(PullRefreshViewHelper.get().getErrorText());
        errorTextView.setTextColor(PullRefreshViewHelper.get().getErrorColor());
        errorTextView.setLayoutParams(layoutParams);
        errorRelativeLayout.addView(errorTextView);
        layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        errorRelativeLayout.setLayoutParams(layoutParams);
        addView(errorRelativeLayout);
        //上拉刷新
        layoutParams = new RelativeLayout.LayoutParams(dp2Px(40), dp2Px(40));
        layoutParams.setMargins(0, 0, 0, dp2Px(16));
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        spinKitView.setColor(PullRefreshViewHelper.get().getLoadColor());
        spinKitView.setIndeterminateDrawable(new DoubleBounce());
        spinKitView.setLayoutParams(layoutParams);
        spinKitView.setVisibility(GONE);
        addView(spinKitView);
        //刷新事件
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(() -> {
                    if (onRefreshListener != null) {
                        onRefreshListener.onRefresh();
                    }
                    swipeRefreshLayout.setRefreshing(false);
                }, 2000);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (canLoadMore) {
                    if (dy > 0) {
                        if (recyclerView.canScrollVertically(1) == false) {
                            spinKitView.setVisibility(VISIBLE);
                            new Handler().postDelayed(() -> {
                                if (onRefreshListener != null) {
                                    onRefreshListener.onLoadMore();
                                }
                                spinKitView.setVisibility(GONE);
                            }, 2000);
                        }
                    }
                }
            }
        });

    }

    private void showView(int state) {

        swipeRefreshLayout.setVisibility(state == STATE_COMPLETE ? VISIBLE : GONE);
        loadRelativeLayout.setVisibility(state == STATE_LOAD ? VISIBLE : GONE);
        emptyRelativeLayout.setVisibility(state == STATE_EMPTY ? VISIBLE : GONE);
        errorRelativeLayout.setVisibility(state == STATE_ERROR ? VISIBLE : GONE);

    }

    private void setLoadStyle() {

        switch (PullRefreshViewHelper.get().getLoadStyle()) {
            case PullRefreshViewHelper.LOAD_STYLE_ROTAP:
                loadSpinKitView.setIndeterminateDrawable(new RotatingPlane());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_DOUBLE:
                loadSpinKitView.setIndeterminateDrawable(new DoubleBounce());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_WAVE:
                loadSpinKitView.setIndeterminateDrawable(new Wave());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_WAND:
                loadSpinKitView.setIndeterminateDrawable(new WanderingCubes());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_PULSE:
                loadSpinKitView.setIndeterminateDrawable(new Pulse());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_CHASING:
                loadSpinKitView.setIndeterminateDrawable(new ChasingDots());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_THREE:
                loadSpinKitView.setIndeterminateDrawable(new ThreeBounce());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_CIRCLE:
                loadSpinKitView.setIndeterminateDrawable(new Circle());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_CUBE:
                loadSpinKitView.setIndeterminateDrawable(new CubeGrid());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_FADING:
                loadSpinKitView.setIndeterminateDrawable(new FadingCircle());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_FOLDING:
                loadSpinKitView.setIndeterminateDrawable(new FoldingCube());
                break;
            case PullRefreshViewHelper.LOAD_STYLE_ROTAC:
                loadSpinKitView.setIndeterminateDrawable(new RotatingCircle());
                break;
            default:
                loadSpinKitView.setIndeterminateDrawable(new CubeGrid());
                break;
        }

    }

    //公共方法

    public void setLoad() {

        isError = false;
        if (recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
            if (recyclerView.getAdapter().getItemCount() == 0) {
                showView(STATE_LOAD);
            }
        } else {
            showView(STATE_LOAD);
        }

    }

    public void setEmpty() {

        isError = false;
        if (recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
            if (recyclerView.getAdapter().getItemCount() == 0) {
                showView(STATE_EMPTY);
            }
        } else {
            showView(STATE_EMPTY);
        }

    }

    public void setComplete() {

        isError = false;
        if (recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
            if (recyclerView.getAdapter().getItemCount() != 0) {
                showView(STATE_COMPLETE);
            } else {
                showView(STATE_EMPTY);
            }
        }

    }

    public boolean isCanRefresh() {

        return canRefresh;

    }

    public void setCanRefresh(boolean canRefresh) {

        swipeRefreshLayout.setEnabled(canRefresh);
        this.canRefresh = canRefresh;

    }

    public boolean isCanLoadMore() {

        return canLoadMore;

    }

    public void setCanLoadMore(boolean canLoadMore) {

        this.canLoadMore = canLoadMore;

    }

    public boolean isError() {

        return isError;

    }

    public void setError(String reason) {

        isError = true;
        if (recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
            if (recyclerView.getAdapter().getItemCount() == 0) {
                errorTextView.setText(reason);
                showView(STATE_ERROR);
            }
        } else {
            errorTextView.setText(reason);
            showView(STATE_ERROR);
        }

    }

    public RecyclerView getRecyclerView() {

        return recyclerView;

    }

    //RecyclerView

    public void setLinearLayoutManager() {

        recyclerView.setLayoutManager(new LinearLayoutManager(context));

    }

    public void setGridLayoutManager(int span) {

        recyclerView.setLayoutManager(new GridLayoutManager(context, span));

    }

    public void setStaggeredGridLayoutManager(int span, int orientation) {

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(span, orientation));

    }

    public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {

        recyclerView.setLayoutManager(layoutManager);

    }

    public void setItemDecoration(RecyclerView.ItemDecoration itemDecoration) {

        recyclerView.addItemDecoration(itemDecoration);

    }

    public void removeItemDecoration(RecyclerView.ItemDecoration itemDecoration) {

        recyclerView.removeItemDecoration(itemDecoration);

    }

    public void setAdapter(RecyclerView.Adapter adapter) {

        recyclerView.setAdapter(adapter);

    }

    //外部接口

    public void setOnRefreshListener(OnRefreshListener listener) {

        this.onRefreshListener = listener;

    }

    public interface OnRefreshListener {

        void onRefresh();

        void onLoadMore();

    }

}
